import {
    formatGMTDate,
    arrayToObject,
    toPercent,
    compareObject
} from "../../../../assets/js/util.js";
import advance from './advancedFilter.vue'
import echarts from 'echarts'
export default {
    data() {
        return {
            /*当前页显示数量*/
            pageSize: 10,
            /*每页显示的数量*/
            pageSizes: [10, 20, 50, 100],
            /*dataTotal表数量*/
            dataTotal: 0,
            /*分页器*/
            currentPage: 1,
            loading: false,
            // 默认参数 和 URL
            SRC: '',
            DP: {
                p: '',
                f: ''
            },
            title: '国家',
            pageWidth: '100%',
            // 开始时间
            startdate: '',
            // 结束时间
            enddate: '',
            // 服务器数组
            servers: [],
            // 请求的参数
            postObj: {
                'startdate': '2017-06-25',
                'enddate': '2017-07-24',
                'serverid': '0'
            },
            /*realTimeServiceContent 的宽*/
            realTimeServiceContent: '100%',
            /*表的宽度*/
            realTimeServiceTableWidth: "100%",
            // 表头
            tableHeader: [
                { prop: "tagvalue", label: "国家名称", width: "130", fixed: true },
                { prop: "newUser", label: "新增帐号数", width: "130", fixed: false },
                { prop: "newUserAccount", label: "新增整体占比", width: "150", fixed: false },
                { prop: "activeUserCount", label: "活跃账号数", width: "130", fixed: false },
                { prop: "payCount", label: "付费金额", width: "130", fixed: false },
                { prop: "payAccout", label: "付费整体占比", width: "150", fixed: false },
                { prop: "payUserCount", label: "付费账号数", width: "130", fixed: false },
                { prop: "activePayRadio", label: "活跃付费率", width: "130", fixed: false },
                { prop: "payARPU", label: "付费ARPU", width: "130", fixed: false },
                { prop: "activeARPU", label: "活跃ARPU", width: "130", fixed: false },
                { prop: "avgOnlineTime", label: "人均在线时长", width: "160", fixed: false },
                { prop: "the2Left", label: "新增帐号次日留存率", width: "200", fixed: false },
                { prop: "the3Left", label: "新增帐号3日留存率", width: "200", fixed: false },
                { prop: "the7Left", label: "新增帐号7日留存率", width: "200", fixed: false },
                { prop: "the14Left", label: "新增帐号14日留存率", width: "200", fixed: false },
                { prop: "the30Left", label: "新增帐号30日留存率", width: "200", fixed: false },
                { prop: "the7LTV", label: "7日LTV", width: "130", fixed: false },
                { prop: "the14LTV", label: "14日LTV", width: "130", fixed: false },
                { prop: "the30LTV", label: "30日LTV", width: "130", fixed: false }
            ],
            // 表格数据
            tableData: [],
            // 表格所有数据
            tableDataAll: []
        }
    },
    computed: {},
    methods: {
        // 通用 成功 与 失败
        successFun(data) {
            this.$message({
                message: data,
                type: 'success'
            });
        },
        errorFun(data) {
            this.$message.error(data);
        },
        // 分页器
        // 控制每页的数量
        handleSizeChange(val) {
            this.pageSize = val;
            this.tableControl();
        },
        // 页数
        handleCurrentChange(val) {
            this.currentPage = val;
            this.tableControl();
        },
        tableControl() {
            this.tableData = this.tableDataAll.slice((this.currentPage - 1) * this.pageSize, this.currentPage * this.pageSize)
        },
        // 开始时间
        startDateChange(val) {
            if (val === undefined) {
                this.errorFun('请选择查看时间！')
            } else {
                this.startdate = val;
                this.postObj.startdate = val;
            }
            this.getData(this.postObj);
        },
        // 结束时间
        endDateChange(val) {
            if (val === undefined) {
                this.errorFun('请选择对比时间！')
            } else {
                this.enddate = val;
                this.postObj.enddate = val;
            }
            this.getData(this.postObj)
        },
        // 选择游戏的平台
        handleSelect(key, keyPath) {
            if (key === '4') {
                this.$refs.advance.filterShow = true;
            } else {
                this.postObj['platformid'] = key;
                this.postObj['serverid'] = '0';
                this.postObj['channelid'] = '0';
                this.getData(this.postObj);
            }
        },
        // 获取服务器list 
        getList() {
            var that = this;
            var pushData = function(pushArr, attr, data) {
                that[pushArr] = [];
                for (var i in data[attr]) {
                    that[pushArr].push({
                        value: i,
                        label: data[attr][i]
                    })
                }
            };
            // `${this.SRC}countryreport/dropdownlist.do`
            this.$http.jsonp(`${this.SRC}data/get.do`, {
                params: {
                    p: this.DP.p,
                    f: this.DP.f,
                    a: "dropdownlist",
                    ps: ""
                }
            }).then(function(res) {
                var data = JSON.parse(res.body)
                data = JSON.parse(data.replace(/\"\{\"/g, '\{\"').replace(/\}\}\"/g, '\}\}'));
                if (parseInt(data["code"]) === 0) {
                    // 后台select的数据
                    var lists = ["msg"];
                    // 页面select名字
                    var nameLists = ["servers"];
                    for (var i = 0; i < lists.length; i++) {
                        if (data[lists[i]] !== undefined) {
                            pushData(nameLists[i], lists[i], data);
                        }
                    }
                } else {
                    this.errorFun(data['msg']);
                }
            })
        },
        // 获取后台数据
        getData(data) {
            var that = this;

            function toPercent(point) {
                var str = Number(point * 100).toFixed(2);
                str += "%";
                return str;
            }
            var sliceData = function(arrData) {
                if (arrData.length === 0) return;
                that.dataTotal = arrData.length;
                var arr = [];
                var header = that.tableHeader;
                for (var i = 0; i < arrData.length; i++) {
                    var arrChind = [];
                    for (var n = 0; n < header.length; n++) {
                        for (var j in arrData[i]) {
                            if (j === header[n]['prop']) {
                                if ('activePayRadio' === j || 'payAccout' === j || 'newUserAccount' === j || 'the2Left' === j || 'the3Left' === j || 'the7Left' === j || 'the14Left' === j || 'the30Left' === j) {
                                    arrData[i][j] = toPercent(arrData[i][j]);
                                }
                                arrChind.push(arrData[i][j]);
                            }
                        }
                    }
                    arr.push(arrChind);
                }
                that.tableDataAll = arrayToObject(that.tableHeader, arr);
                that.tableControl();
            }
            var p = new Promise(function(resolve, reject) {
                that.dataTotal = 0;
                that.loading = true;
                that.tableData = [];
                that.tableDataAll = [];
                that.$http.jsonp(`${that.SRC}data/get.do?p=${that.DP.p}&f=${that.DP.f}&a=list`, {
                    params: { 'ps': `startdate=${data.startdate}&enddate=${data.enddate}&serverid=${data.serverid}` }
                }).then(function(res) {
                    resolve(res.body)
                })
            })
            p.then(function(value) {
                that.loading = false;
                var data = JSON.parse(value)
                data = JSON.parse(data.replace(/\"\{\"/g, '\{\"').replace(/\"\}\"/g, '\"\}'));
                if (parseInt(data["code"]) === 0) {
                    sliceData(data.msg)
                } else {
                    that.errorFun(data['msg']);
                }
            })
        },
        /*设置初始值*/
        _init() {
            window.addEventListener('resize', function() {
                /*修改表格的宽度*/
                this.realTimeServiceTableWidth = document.body.clientWidth - 240 + "px";
                this.realTimeServiceContent = document.body.clientWidth - 220 + "px";
            }.bind(this))
        },
        // 表格下载
        excel() {
            this.downloadExl(this.tableHeader, this.tableDataAll, this.title, this.title);
        },
        // 表格排序
        sortChange(column) {
            if (column.prop === null) {
                return;
            } else if (column.order === 'descending') {
                this.tableDataAll.sort(compareObject(column.prop, false));
            } else { //正序
                this.tableDataAll.sort(compareObject(column.prop, true));
            }
            this.tableControl();
        }
    },
    components: {
        'v-advance': advance,
    },
    computed: {
        xlsx() {
            return this.title + '.xlsx'
        }
    },
    mounted() {
        this._init()
            // 初始化URL
        this.SRC = this.$store.getters.src;
        this.DP.p = localStorage.getItem('ZULONGBIPROJECTID');
        this.DP.f = localStorage.getItem('ZULONGBIPAGEID');
        // 初始化时间
        this.enddate = new Date();
        this.startdate = new Date(new Date().getTime() - 16 * 86400000);
        this.postObj.enddate = formatGMTDate(new Date(), true);
        this.postObj.startdate = formatGMTDate(new Date().getTime() - 16 * 86400000, true);

        // 获取到服务器 list
        this.getList();
        this.getData(this.postObj);
    }
}